package cn.wu.reggie.service.impl;


import cn.hutool.core.collection.CollUtil;
import cn.wu.reggie.common.R;
import cn.wu.reggie.entity.Category;
import cn.wu.reggie.entity.Dish;
import cn.wu.reggie.entity.Setmeal;
import cn.wu.reggie.exception.BusinessException;
import cn.wu.reggie.mapper.CategoryMapper;
import cn.wu.reggie.mapper.DishMapper;
import cn.wu.reggie.mapper.SetmealMapper;
import cn.wu.reggie.query.CategoryQuery;
import cn.wu.reggie.service.ICategoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {


    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 分页
     * @param qo
     * @return
     */
    @Override
    public Page<Category> queryPage(CategoryQuery qo) {

        // 创建条件查询
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        // 创建分页
        Page<Category> page = new Page<>(qo.getPage(), qo.getPageSize());
        // 模糊查询
        return super.page(page,wrapper);
    }


    @Override
    public R saveOne(Category category) {
        // 封装时间
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(category.getCreateTime());
        // 调用mapper完成保存
        categoryMapper.insert(category);
        return R.success(null);
    }

    @Override
    public R updateOne(Category category) {
        // 封装时间
        category.setUpdateTime(LocalDateTime.now());
        // 调用mapper完成修改
        categoryMapper.updateById(category);
        return R.success(null);
    }


    // 不需要加事务的注解 因为只是查询操作不影响 就算是删除也不影响因为抛错误后会回滚
    @Override
    public R delete(Long id) {

        // 通过分类id看此分类下有没有菜品或者套餐
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("category_id",id);

        List<Setmeal> setmealList = setmealMapper.selectList(wrapper);
        if (CollUtil.isNotEmpty(setmealList)){
            throw new BusinessException("该分类下有套餐 不能删除");
        }

        List<Dish> dishList = dishMapper.selectList(wrapper);
        if (CollUtil.isNotEmpty(dishList)){
            throw new BusinessException("该分类下有菜品，不能删除");
        }

        // 调用categoryMapper完成删除
        categoryMapper.deleteById(id);
        return R.success(null);
    }
}